import React, { useEffect, useState } from "react";
import { Button, Form, ImageUploader, Popup, Toast } from "antd-mobile";
import $fetch from "../../../../utils/app/$fetch";
import { useLogin } from "../../../../context/LoginContext";
import CropImage from "../../../../utils/ui/CropImage";
import $readFile from "../../../../utils/app/$readFile";
import { CloseOutline } from 'antd-mobile-icons';
import "./style.scss";

export default function AvatarComponent({ bg }: any) {
  const [form]: any = Form.useForm();
  const { state, dispatch }: any = useLogin();
  
  const beforeUpload = async (file: File) => {
    if (file.size > 1024 * 1024 * 10) {
      Toast.show("请选择小于 10M 的图片");
      return null;
    } else {
      let imageDataUrl = await $readFile(file);
      dispatch({ image: imageDataUrl, avatar: file, showCropper: true });
    }
    return null;
  };

  const handleUpload: any = async (file: any) => {
    // try {
    //   const formData = new FormData();
    //   if (file instanceof File) {
    //     formData.append("file", file);
    //     const res: any = await $fetch("/minio/upload", formData, {
    //       method: "post",
    //       noGroupId: "no",
    //       dataType: "form",
    //     });
    //     dispatch({ avatar: [{ url: res?.url }] });
    //     return { url: res?.url };
    //   }
    // } catch (error) {
    //   console.log(error, "______error");
    // }
  };

  const onSubmit = async () => {
    // if (state?.avatar?.[0]?.url || state?.name) {
    try {
      await $fetch(
        `/customer/updateInfo?${
          state?.avatar?.[0]?.url ? `avatar=${state.avatar[0].url}` : ""
        }${state?.name ? `&name=${state.name}` : ""}`,
        {},
        { method: "post", noGroupId: "no" }
      );
    } catch (error) {
      console.log(error, "_____error");
    }
    // }
    dispatch({ showAvatar: false, name: "", avatar: [] });
    form.resetFields();
    // navigate('/home', { replace: true })
    window.location.replace("/#/home");
  };

  return (
    <Popup visible={state?.showAvatar} destroyOnClose={true}>
      <div className="container_popup_avatar" style={{ height: "100vh" }}>
        <img src={bg} alt="" style={{ width: "100%" }} />
        <div>
          <div className="that_header">
            <h2>再上传您的头像</h2>
          </div>

          <Form
            layout="horizontal"
            form={form}
            footer={
              <Button
                onClick={onSubmit}
                block
                type="submit"
                color="primary"
                shape="rounded"
              >
                完成
              </Button>
            }
          >
            <Form.Item name="avatar">
              {Object.keys(state?.img).length !== 0 ? (
                <div className='crooped_wraper'>
                  <div className='cropped_img'>
                    <img
                      src={state?.img}
                      alt=""
                    />
                    <div onClick={()=>dispatch({ img: '' })}>
                      <CloseOutline />
                    </div>
                  </div>

                </div>
              ) : (
                <ImageUploader
                  value={state?.avatar || [{ url: "" }]}
                  onChange={(file: any) => {
                    dispatch({ avatar: file });
                  }}
                  beforeUpload={beforeUpload}
                  multiple={false}
                  upload={handleUpload}
                  maxCount={1}
                />
              )}
              {/* <ImageUploader
                  value={state?.avatar || [{ url: "" }]}
                  onChange={(file: any) => {
                    dispatch({ avatar: file });
                  }}
                  beforeUpload={beforeUpload}
                  multiple={false}
                  upload={handleUpload}
                  maxCount={1}
                /> */}
            </Form.Item>
          </Form>
        </div>
      </div>

      {state?.showCropper && (
        <CropImage
          src={state?.image}
          avatar={state?.avatar}
          visible={state?.showCropper}
          form={form}
          dispatch={dispatch}
        />
      )}
    </Popup>
  );
}
